package com.shujia.mvc;


import com.shujia.util.JDBCUtil;

import java.sql.*;

/**
 * 持久层：和数据库交互
 */
public class UserDao {


    /**
     * 通过用户名查询用户
     *
     * @param username 用户名
     * @return 用户的对象
     */

    public User findUserByUsername(String username) {
        User user = null;
        try {

            Connection con = JDBCUtil.getConnection();

            PreparedStatement stat = con.prepareStatement("select * from t_user where username=?");

            stat.setString(1, username);

            ResultSet resultSet = stat.executeQuery();

            /*
             * 如果查询到这个用户返回对应用户，如果没有查询到返回null
             *
             */
            if (resultSet.next()) {
                int id = resultSet.getInt("id");

                String username1 = resultSet.getString("username");

                String password = resultSet.getString("password");

                user = new User(id, username1, password);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;
    }


    /**
     * @param user yoghurt
     * @return 石佛插入成功
     */

    public int insert(User user) {

        int flag = 0;

        //1、获取连接
        Connection con = JDBCUtil.getConnection();

        try {
            PreparedStatement stat = con.prepareStatement("insert into t_user(username,password) values(?,?)");

            stat.setString(1, user.getUsername());
            stat.setString(2, user.getPassword());

            //执行插入
            flag = stat.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 更新密码
     *
     * @param username    用户米
     * @param newPassword 新密码
     * @return 是否成功
     */

    public int updatePasswordByUsername(String username, String newPassword) {

        int flag = 0;

        //获取连接
        Connection con = JDBCUtil.getConnection();

        try {
            PreparedStatement stat = con.prepareStatement("update t_user set password=? where username=?");
            stat.setString(1, newPassword);
            stat.setString(2, username);

            flag = stat.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return flag;
    }

}
